// 完整的checkAPIStatus函数修复
const checkAPIStatus = async (apiStatus) => {
  // 确保apiStatus是一个响应式对象
  if (!apiStatus || typeof apiStatus.value === 'undefined') {
    console.error('apiStatus对象无效，必须是响应式对象');
    return;
  }
  
  apiStatus.value = { status: '正在检查...' };
  
  try {
    // 获取token
    const token = localStorage ? localStorage.getItem('token') || '' : '';
    
    // 使用原始的fetch API避免被拦截器处理
    const response = await fetch('https://zmyzmy.xin/api/auth/status', {
      headers: {
        'Authorization': `Bearer ${token}`
      }
    });
    
    if (response.ok) {
      const data = await response.json();
      apiStatus.value = {
        ...data,
        lastChecked: new Date().toISOString()
      };
      console.log('[API] API状态检查成功', data);
      if (typeof ElMessage !== 'undefined') {
        ElMessage.success('API状态检查成功');
      }
      return { success: true, data };
    } else {
      apiStatus.value = { 
        status: 'error', 
        statusCode: response.status,
        statusText: response.statusText,
        lastChecked: new Date().toISOString()
      };
      
      try {
        const errorData = await response.json();
        apiStatus.value.errorData = errorData;
      } catch (e) {
        // 忽略解析错误
      }
      
      console.error('[API] API状态检查失败', apiStatus.value);
      if (typeof ElMessage !== 'undefined') {
        ElMessage.error(`API状态检查失败: ${response.status} ${response.statusText}`);
      }
      return { success: false, error: apiStatus.value };
    }
  } catch (error) {
    apiStatus.value = { 
      status: 'error', 
      message: error.message,
      lastChecked: new Date().toISOString()
    };
    console.error('[API] API状态检查出错', error.message);
    if (typeof ElMessage !== 'undefined') {
      ElMessage.error(`API状态检查出错: ${error.message}`);
    }
    return { success: false, error: apiStatus.value };
  }
};

// 验证登录状态
const checkLoginStatus = async () => {
  try {
    const token = localStorage ? localStorage.getItem('token') || '' : '';
    
    if (!token) {
      console.warn('[检查] 未找到认证token');
      return { loggedIn: false, reason: 'no-token' };
    }
    
    console.log(`[检查] 正在验证登录状态`);
    // 有些系统没有专门的验证endpoint，可以用测试endpoint代替
    const response = await fetch('https://zmyzmy.xin/api/auth/test', {
      headers: {
        'Authorization': `Bearer ${token}`
      }
    });
    
    if (response.ok) {
      try {
        const data = await response.json();
        console.log('[检查] 登录状态有效:', data);
        return { loggedIn: true, data };
      } catch (e) {
        // 如果响应不是JSON，但状态码是200，仍然认为是登录成功
        if (response.status === 200) {
          return { loggedIn: true };
        }
        console.warn('[检查] 响应解析错误:', e.message);
        return { loggedIn: false, reason: 'parse-error' };
      }
    } else {
      console.warn('[检查] 登录状态无效:', {
        status: response.status
      });
      return { loggedIn: false, reason: 'invalid-token', status: response.status };
    }
  } catch (error) {
    console.error('[检查] 登录状态检查异常:', error.message);
    return { loggedIn: false, reason: 'error', message: error.message };
  }
};

// 测试API连接
const testAPIConnection = async (baseURL = 'https://zmyzmy.xin/api') => {
  try {
    console.log(`[测试] 正在检查API连接: ${baseURL}`);
    const response = await fetch(`${baseURL}/auth/test`);
    
    if (response.ok) {
      const data = await response.json();
      console.log('[测试] API连接成功:', data);
      return { success: true, data };
    } else {
      console.error('[测试] API连接失败:', {
        status: response.status,
        statusText: response.statusText
      });
      return { 
        success: false, 
        error: { 
          status: response.status,
          statusText: response.statusText
        } 
      };
    }
  } catch (error) {
    console.error('[测试] API连接异常:', error.message);
    return { success: false, error: { message: error.message } };
  }
};

// 导出所有函数
export {
  checkAPIStatus,
  checkLoginStatus,
  testAPIConnection
};
